import React, { useState, useEffect } from'react';
import { PlusOutlined } from '@ant-design/icons';
import style from './add.module.less';
import { getGoodsCate } from "@/api/account";
import { addgoods, imgupload } from '../../../api/account';
import { Form, Input, Select, Upload, InputNumber, Space, Button, message } from 'antd';
import { serverUrl } from "@/utils/comment";

const normFile = (e) => {
    console.log('normFile received:', e); // 添加日志输出
    if (Array.isArray(e)) {
        return e;
    }
    return e?.fileList;
};

// 改变价格
const onChange = (value) => {
    console.log('changed', value);
};

export default function Add() {
    const [type, settype] = useState([]);
    const [form] = Form.useForm();

    // 获取商品分类
    const getCategory = () => {
        getGoodsCate().then((res) => {
            settype(res.categories);
        });
    };

    // 上传图片
    const uploadImage = async (file) => {
        const formData = new FormData();
        formData.append('file', file);
        try {
            const response = await imgupload(formData);
            if (response.code === 0) {
                return response.imgUrl;
            } else {
                message.error(response.msg);
                return null;
            }
        } catch (error) {
            message.error('图片上传失败');
            return null;
        }
    };

    // 添加商品
    const addgood = async (gooddata) => {
        try {
            const response = await addgoods(gooddata);
            console.log('添加商品接口响应:', response); // 打印完整响应信息，便于排查问题
            if (response.code === 0) {
                message.success(response.msg);
            } else {
                message.error(response.msg);
            }
        } catch (error) {
            message.error('添加商品失败');
        }
    };

    useEffect(() => {
        getCategory();
    }, []);

    const onFinish = async (values) => {
        const fileList = values['imgUrl'] || [];
        const priceValue = values['price'];
        let imgUrl = '';
        if (fileList.length > 0) {
            const file = fileList[0].originFileObj;
            imgUrl = await uploadImage(file);
            if (!imgUrl) {
                return;
            }
        }
        const formData = {
            name: values['name'],
            category: values['category'],
            price: priceValue!== undefined? priceValue.toString() : '0',
            imgUrl,
            goodsDesc: values['goodsDesc']
        };
        console.log('添加商品请求参数:', formData); // 打印请求参数，便于检查
        addgood(formData);
    };

    return (
        <div>
            <div className={style.title}>
                商品添加
            </div>
            <Form
                form={form}
                labelCol={{ span: 4 }}
                wrapperCol={{ span: 14 }}
                layout="horizontal"
                style={{ maxWidth: 600, marginTop: 20 }}
                onFinish={onFinish}
            >
                <Form.Item label="商品名称" name='name'>
                    <Input />
                </Form.Item>
                <Form.Item label="商品分类" name='category'>
                    <Select>
                        {type.map((category, index) => (
                            <Select.Option
                                key={index}
                                value={category.cateName}
                            >
                                {category.cateName}
                            </Select.Option>
                        ))}
                    </Select>
                </Form.Item>
                <Form.Item label="商品价格" name='price'>
                    <Space wrap>
                        <InputNumber min={1} max={100000} defaultValue={3} onChange={onChange} />
                    </Space>
                </Form.Item>
                <Form.Item
                    label="imgUrl"
                    valuePropName="fileList"
                    getValueFromEvent={normFile}
                >
                    <Upload
                        action="/api/goods/goods_img_upload"
                        listType="picture-card"
                        beforeUpload={(file) => {
                            console.log('Before upload:', file); // 检查 beforeUpload 中的文件信息
                            return true; // 确保不拦截上传
                        }}
                    >
                        <button
                            style={{ color: 'inherit', cursor: 'inherit', border: 0, background: 'none' }}
                            type="button"
                        >
                            <PlusOutlined />
                            <div style={{ marginTop: 8 }}>上传图片</div>
                        </button>
                    </Upload>
                </Form.Item>
                <Form.Item
                    name="goodsDesc"
                    label="商品描述"
                >
                    <Input.TextArea showCount maxLength={100} />
                </Form.Item>
                <Form.Item>
                    <Button type="primary" htmlType="submit">
                        添加
                    </Button>
                </Form.Item>
            </Form>
        </div>
    );
}    